<?php
/**
 * Elgg csv import action
 * 
 */
// Constant
$KTPM = 1;
$KHMT = 2;
$MMTTT = 3;
$HTTT = 4;

$usertype = get_input ( 'usertype', "" );

switch ($separator) {
	case 'tab' :
		$separator = "\t";
		break;
	default :
		$separator = ',';
		break;
}

$file = "";

if (isset ( $_FILES ['csvimport'] ) && $_FILES ['csvimport'] ['error'] == 0) {
	$file = $_FILES ['csvimport'] ['tmp_name'];
}

if ($file) {
	include 'classes/PHPExcel/IOFactory.php';
	
	$objPHPExcel = PHPExcel_IOFactory::load ( $file );
	
	$sheetData = $objPHPExcel->getActiveSheet ()->toArray ( null, true, true, true );
	$message = "";
	$header = true;
	
	foreach ( $sheetData as $row ) {
		if ($header) {
			$header = false;
			continue;
		}
		
		$username = preg_replace ( '/[\',\s]/', '', $row ['A'] );
		$password = $username;
		$name = $row ['B'];
		
		$email = $username . "@gm.uit.edu.vn";
		$faculty = $row ['D'];
		
		if (isset ( $username ) && isset ( $password ) && isset ( $name ) && isset ( $email )) {
			try {
				$new_user_guid = register_user ( $username, $password, $name, $email, true );
			} catch ( Exception $e ) {
			}
			
			if ($new_user_guid) {
				$user = get_entity ( $new_user_guid );
				// elgg_set_user_validation_status ( $user->guid, true );
				switch ($faculty) {
					case 'KTPM' :
						$user->faculty = CNPM;
						break;
					case 'CNPM' :
						$user->faculty = CNPM;
						break;
					case 'KHMT' :
						$user->faculty = KHMT;
						break;
					case 'MMTTT' :
						$user->faculty = MMTTT;
						break;
					case 'HTTT' :
						$user->faculty = HTTT;
						break;
					case "ANTT" :
						$user->faculty = ANTT;
						break;
					case "CNTN" :
						$user->faculty = CNTN;
						break;
					default :
						break;
				}
				$user->usertype = $usertype;
				$user->save ();
			}
		}
	}
	
	system_message ( "Tạo thành viên thành công" );
} else {
	register_error ( elgg_echo ( 'csvimport:import:error' ) );
}

forward ( REFERER );

